from flask import current_app, session, jsonify, request
from flask import render_template

from info.constants import HOME_PAGE_MAX_NEWS
from info.models import User, News, Category
from info.modules.home import home_blu
from info.utils.response_code import RET, error_map


@home_blu.route('/')
def index():
    user_id = session.get("user_id")
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except BaseException as e:
            current_app.logger.error(e)

    user = user.to_dict() if user else None

    rank_list = []
    try:
        rank_list = News.query.order_by(News.clicks.desc()).limit(HOME_PAGE_MAX_NEWS).all()
    except BaseException as e:
        current_app.logger.error(e)
    rank_list = [news.to_basic_dict() for news in rank_list]

    categories = []
    try:
        categories = Category.query.all()
    except BaseException as e:
        current_app.logger.error(e)

    return render_template("news/index.html", user=user, rank_list=rank_list, categories=categories)


@home_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file("news/favicon.ico")


@home_blu.route('/get_news_list')
def get_news_list():
    cid = request.args.get("cid")
    cur_page = request.args.get("cur_page")
    per_count = request.args.get("per_count", HOME_PAGE_MAX_NEWS)

    if not all([cid, cur_page, per_count]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        cid = int(cid)
        cur_page = int(cur_page)
        per_count = int(per_count)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    filter_list = [News.status == 0]
    if cid != 1:
        filter_list.append(News.category_id == cid)

    try:
        pn = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(cur_page, per_count)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    data = {
        "news_list" : [news.to_dict() for news in pn.items],
        "total_page" : pn.pages
    }

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)
